package com.haixee.parkdemo.common.response;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Request 工具类
 *
 * @author GUIFENG GUO
 * 2020/3/22 21:13
 */
@Slf4j
public class RequestUtil {

    // 验证请求参数
    public static String processError(BindingResult bindingResult) {
        if (!bindingResult.hasErrors()) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {

            String message = error.getDefaultMessage();
            if (StringUtils.contains(message, "NumberFormatException")) {
                message = error.getField() + " 格式错误";
            }

            stringBuilder.append(message).append(",");
        }
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    // Filter 处理的结果
    public static void writeResult(HttpServletResponse response, ResResult commonRes) throws IOException {
        writeResult(response, HttpStatus.OK, commonRes);
    }

    public static void writeResult(HttpServletResponse response, HttpStatus status, ResResult commonRes) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(status.value());
        response.getWriter().print(objectMapper.writeValueAsString(commonRes));
        response.getWriter().flush();
    }

    // ip 获取
    public static String getIp(HttpServletRequest request) {

        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(ip)) {
            ip = StringUtils.trim(ip).split(",")[0];
        }

        if (StringUtils.isBlank(ip)) {
            ip = request.getHeader("X-Real-Ip");
        }

        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                return ip;
            }
        }
        return ip;
    }

}
